//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.ComponentModel;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using CommunityServer.Controls;
using CommunityServer.Files.Components;
using System.Web.UI;

namespace CommunityServer.Files.Controls
{
	/// <summary>
	/// Summary description for PortalPictureListing.
	/// </summary>
	public class PortalEntryListing : FileGalleryTemplatedWebControl
	{
		CSContext csContext = CSContext.Current;

		#region Public Properties

		[DefaultValue( 5 )]
		public int Count = 5;

		[DefaultValue( EntriesSortBy.PostDate )]
		public EntriesSortBy SortBy = EntriesSortBy.PostDate;

		public SortOrder SortOrder = SortOrder.Descending;

        private int categoryID = 0;
	    public int CategoryID
	    {
            get
            {
                if (categoryID == 0 && !IgnoreCurrentCategory)
                    categoryID = csContext.CategoryID;

                return categoryID;
            }
            set { categoryID = value; }
	    }

        private int groupID = 0;
        public int GroupID
        {
            get
            {
                if (groupID == 0 && ! IgnoreCurrentGroup)
                    groupID = csContext.GroupID;

                return groupID;
            }
            set { groupID = value; }
        }

        private int sectionID = 0;
        public int SectionID
        {
            get
            {
                if (sectionID == 0 && !IgnoreCurrentSection && !Globals.IsNullorEmpty(csContext.ApplicationKey))
                    sectionID = Folders.GetFolderID(csContext.ApplicationKey);

                return sectionID;
            }
            set { sectionID = value; }
        }

        private bool ignoreCurrentSection = false;
	    public bool IgnoreCurrentSection
	    {
	        get{ return ignoreCurrentSection;}
	        set{ ignoreCurrentSection = value;}
	    }

        private bool ignoreCurrentCategory = false;
        public bool IgnoreCurrentCategory
        {
            get { return ignoreCurrentCategory; }
            set { ignoreCurrentCategory = value; }
        }

        private bool ignoreCurrentGroup = false;
        public bool IgnoreCurrentGroup
        {
            get { return ignoreCurrentGroup; }
            set { ignoreCurrentGroup = value; }
        }

		#endregion

		#region Child Controls

		private IText sectionTitle;
		private RepeaterPlusNone entryList;

		#endregion

		#region Skin

		protected override void AttachChildControls()
		{
			sectionTitle = FindText( "SectionTitle" );
			entryList = (RepeaterPlusNone)FindControl( "Entries" );
			InitializeChildControls();
		}

		private void InitializeChildControls()
		{
			entryList.ItemDataBound += new RepeaterItemEventHandler(pictureList_ItemDataBound);
			entryList.NoneItemsDataBound += new RepeaterItemEventHandler(pictureList_NoneItemsDataBound);
		}

		#endregion

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad (e);
			DataBind();
		}

		public override void DataBind()
		{
			base.DataBind();
			BindEntries();
		}

		public void BindEntries()
		{
			// Set the area title
			if (sectionTitle != null)
			{
				switch(SortBy)
				{
					case EntriesSortBy.PostDate:
						sectionTitle.Text = FileGalleryResourceManager.GetString( "Files_PortalEntryListing_TitlePostDate" );
						break;
					case EntriesSortBy.Rating:
						sectionTitle.Text = FileGalleryResourceManager.GetString( "Files_PortalEntryListing_TitleRating" );
						break;
					case EntriesSortBy.Comments:
						sectionTitle.Text = FileGalleryResourceManager.GetString( "Files_PortalEntryListing_TitleReplies" );
						break;
					case EntriesSortBy.Views:
						sectionTitle.Text = FileGalleryResourceManager.GetString( "Files_PortalEntryListing_TitleViews" );
						break;
					case EntriesSortBy.Downloads:
						sectionTitle.Text = FileGalleryResourceManager.GetString( "Files_PortalEntryListing_TitleDownloads" );
						break;
				}
			}

			FileGalleryThreadQuery query = new FileGalleryThreadQuery();
			if(this.CategoryID > 0)
			    query.CategoryID = this.CategoryID;
            if(this.GroupID > 0)
                query.GroupID = this.GroupID;
			query.PageSize = Count;
			query.SortBy = SortBy;
			query.SortOrder = SortOrder;
			query.OnlyApproved = true;
			query.FilterByList = new System.Collections.ArrayList();
			query.RequireSectionIsActive = true;

            if (this.SectionID == 0)
            {
                foreach (Folder folder in Folders.GetFolders())
                    if (Permissions.ValidatePermissions(folder, Permission.View, csContext.User) && (folder.GroupID == this.GroupID || this.GroupID <= 0))
                        query.FilterByList.Add(folder);
             
                if (query.FilterByList.Count == 0)
                    return;
            }
            else
            {
                query.SectionID = this.SectionID;
            }
		    
			entryList.DataSource = Entries.GetEntries(query).Threads;
			entryList.DataBind();
		}

		private void pictureList_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			Entry dataItem = e.Item.DataItem as Entry;

			switch( e.Item.ItemType ) 
			{
				case ListItemType.Item:
				case ListItemType.AlternatingItem:

					HyperLink nameLink = (HyperLink)e.Item.FindControl( "Name" );
					IText fieldName = TextControlHelper.Create(e.Item.FindControl( "SortedName"));
					IText field = TextControlHelper.Create(e.Item.FindControl( "SortedField"));
					IText description = TextControlHelper.Create(e.Item.FindControl( "Description" ));
					IText fileSize = TextControlHelper.Create(e.Item.FindControl( "FileSize"));
					HyperLink postedBy = (HyperLink)e.Item.FindControl( "PostedBy" );
					IText dateAdded = TextControlHelper.Create(e.Item.FindControl( "DateAdded" ));
					IText downloads = TextControlHelper.Create(e.Item.FindControl( "Downloads"));
					Control downloadLink = e.Item.FindControl("DownloadLink");
					Control editLink = e.Item.FindControl("EditLink");
					Control deleteLink = e.Item.FindControl("DeleteLink");
					FileThumbnail thumbnail = (FileThumbnail) e.Item.FindControl("FileThumbnail");

					User user = csContext.User;

					if (nameLink != null)
					{
						if(dataItem.Subject != "")
							nameLink.Text = dataItem.Subject;
						else
							nameLink.Text = FileGalleryResourceManager.GetString( "NoTitle" );

						nameLink.NavigateUrl = FileGalleryUrls.Instance().ViewEntry(dataItem.Section.ApplicationKey, dataItem.PostID);
					}

					if (description != null)
					{
						string desc = CommunityServer.Components.Formatter.RemoveHtml(dataItem.RenderedBody(PostTarget.Web));
						if(desc.Length > 50)
							description.Text = desc.Substring(0, 50) + "...";
						else
							description.Text = desc;
					}

					if (thumbnail != null)
						thumbnail.Post = dataItem;

					if (downloads != null)
						downloads.Text = dataItem.Downloads.ToString();

					if (dateAdded != null)
					{
						if(!user.IsAnonymous)
							dateAdded.Text = user.GetTimezone(dataItem.PostDate).ToString(user.Profile.DateFormat);
						else
							dateAdded.Text = dataItem.PostDate.ToString(csContext.SiteSettings.DateFormat);
					}

					if (fileSize != null)
					{
						if (dataItem.FileSize >= 0)
						{
							if(dataItem.FileSize < 1024)
								fileSize.Text = dataItem.FileSize.ToString() + " bytes";
							else if(dataItem.FileSize < 1024*1024)
								fileSize.Text = ((double)dataItem.FileSize / 1024).ToString("0.#") + "kB";
							else
								fileSize.Text = ((double)dataItem.FileSize / (1024*1024)).ToString("0.#") + "MB";
						}
						else
							fileSize.Text = "Unknown";
					}

					if (postedBy != null)
					{
						postedBy.Text = dataItem.DisplayName;
						postedBy.NavigateUrl = Globals.GetSiteUrls().UserProfile(dataItem.AuthorID);
					}

					RatingListing ratingListing = (RatingListing)e.Item.FindControl( "RatingListing" );
					if (ratingListing != null)
					{
						ratingListing.PictureID = dataItem.PostID;
						ratingListing.Entry = dataItem;
						ratingListing.ApplicationKey = dataItem.Section.ApplicationKey;
						ratingListing.DataBind();
					}

					if (downloadLink != null)
					{
						if (downloadLink is HyperLink)
						{
							((HyperLink) downloadLink).NavigateUrl = FileGalleryUrls.Instance().Download(dataItem);
							downloadLink.Visible = true;
						}
						else if (downloadLink is FileGalleryImageButton)
						{
							FileGalleryImageButton downloadIB = (FileGalleryImageButton) downloadLink;
							downloadIB.Post = dataItem;
							downloadIB.ApplicationKey = dataItem.Section.ApplicationKey;
							downloadIB.Visible = true;
						}
					}

					if (editLink != null)
					{
						if (Permissions.ValidatePermissions(dataItem.Section, Permission.Edit, user, dataItem))
						{
							if (editLink is HyperLink)
							{
								HyperLink editLinkHL = (HyperLink) editLink;
								editLinkHL.Visible = true;
								editLinkHL.NavigateUrl = FileGalleryUrls.Instance().EntryAdmin(dataItem.Section.ApplicationKey, dataItem.PostID);
							}
							else if (editLink is FileGalleryImageButton)
							{
								FileGalleryImageButton editLinkIB = (FileGalleryImageButton) editLink;
								editLinkIB.Post = dataItem;
								editLinkIB.ApplicationKey = dataItem.Section.ApplicationKey;
								editLinkIB.Visible = true;
							}
						}
						else
						{
							editLink.Visible = false;
						}
					}

					if (deleteLink != null)
					{
						if (Permissions.ValidatePermissions(dataItem.Section, Permission.Delete, user, dataItem))
						{
							if (deleteLink is HyperLink)
							{
								HyperLink deleteLinkHL = (HyperLink) deleteLink;
								deleteLinkHL.Visible = true;
								deleteLinkHL.NavigateUrl = FileGalleryUrls.Instance().DeleteEntry(dataItem.Section.ApplicationKey, dataItem.PostID);
							}
							else if (deleteLink is FileGalleryImageButton)
							{
								FileGalleryImageButton deleteLinkIB = (FileGalleryImageButton) deleteLink;
								deleteLinkIB.Visible = true;
								deleteLinkIB.Post = dataItem;
								deleteLinkIB.ApplicationKey = dataItem.Section.ApplicationKey;
							}
						}
						else
						{
							deleteLink.Visible = false;
						}
					}

					switch(SortBy)
					{
						case EntriesSortBy.PostDate:
							DateTime postDate = dataItem.PostDate;
							string dateFormat;

							if(!user.IsAnonymous)
							{
								postDate = user.GetTimezone(dataItem.PostDate);
								dateFormat = user.Profile.DateFormat;
							}
							else
								dateFormat = csContext.SiteSettings.DateFormat;

							if (fieldName != null)
								fieldName.Text = FileGalleryResourceManager.GetString( "Files_PortalEntryListing_FieldPostDate" );

							if (field != null)
								field.Text = postDate.ToString(dateFormat) + " " + postDate.ToString(csContext.SiteSettings.TimeFormat);

							break;

						case EntriesSortBy.Rating:

							if (fieldName != null)
								fieldName.Text = FileGalleryResourceManager.GetString( "Files_PortalEntryListing_FieldRating" );

							if (field != null)
								field.Text = dataItem.RatingAverage.ToString("0.0#");

							break;

						case EntriesSortBy.Comments:

							if (fieldName != null)
								fieldName.Text = FileGalleryResourceManager.GetString( "Files_PortalEntryListing_FieldReplies" );

							if (field != null)
								field.Text = dataItem.Replies.ToString();

							break;

						case EntriesSortBy.Views:

							if (fieldName != null)
								fieldName.Text = FileGalleryResourceManager.GetString( "Files_PortalEntryListing_FieldViews" );

							if (field != null)
								field.Text = dataItem.Views.ToString();

							break;

						case EntriesSortBy.Downloads:
							
							if (fieldName != null)
								fieldName.Text = FileGalleryResourceManager.GetString( "Files_PortalEntryListing_FieldDownloads" );

							if (field != null)
								field.Text = dataItem.Downloads.ToString();

							break;
					}

					break;
			}
		}

		private void pictureList_NoneItemsDataBound(object sender, RepeaterItemEventArgs e)
		{

		}
	}
}
